include('shared.lua')
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

function ENT:Initialize()
	self:SetModel( self.Model )
	
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)

	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:EnableMotion(false)
	end	
	
	self:UpdateNW()
	self.NextFreeTouch = 0
	
end

function ENT:AddToTeam( TeamId, count )
	
	local AddQuantatiy = FrameTime() * count
	
	if TeamId == TEAM_BLUE then
		self.Blue = math.min( self.Blue + AddQuantatiy, 1 )
		self.Red = math.max( self.Red - AddQuantatiy, 0 )
	elseif TeamId == TEAM_RED then
		self.Red = math.min(self.Red + AddQuantatiy, 1 )
		self.Blue = math.max( self.Blue - AddQuantatiy, 0 )
	end
	
	if self.Blue == 1 && self.Team != TEAM_BLUE then
		self.Team = TEAM_BLUE
	elseif self.Red == 1 && self.Team != TEAM_RED then
		self.Team = TEAM_RED
	end

end

function ENT:Think()
	
	local Players = {0,0}
	local TotalCount = 0
	local MyPos = self:GetPos()
	
	for _, v in pairs( player.GetAll() ) do
		
		if v:GetPos():Distance( MyPos ) < 128 then
			
			local Team = v:Team()
			
			if !Players[ Team ] then
				Players[ Team ] = 1
			else
				Players[ Team ] = Players[ Team ] + 1
			end
			
			TotalCount = TotalCount + 1
			
		end		
		
	end
	
	if Players[TEAM_BLUE] > 0 && Players[TEAM_RED] > 0 then
		return
	
	elseif Players[TEAM_BLUE] > 0 then
		self.NextFreeTouch = CurTime()
		self:AddToTeam( TEAM_BLUE, Players[TEAM_BLUE] )
	
	elseif Players[TEAM_RED] > 0 then
		self.NextFreeTouch = CurTime()
		self:AddToTeam( TEAM_RED, Players[TEAM_RED] )
		
	elseif CurTime() > self.NextFreeTouch && self.Team != 0 then
		
		self:AddToTeam( self.Team, 0.5 )
		
	end
	
end

